Page({
  data: {
    community: {
        id:1,
        title:"繁华社区",
        member:100,
        leader:{
          name: "王卓煜"
        }
    },
    products: [],
    isGroupActive: true,
    isMyActive: false,
    userInfo: {
      id:null,
      nickName:null,
      avatarUrl:null,
      sessionKey:null,
      openId:null
    },
    guest:true,
    queryPageBean:{
      currentPage: 1,
      pageSize:5,
      queryString: null,
    },
    intervalIds: [] // 用于保存所有定时器的 ID
  },
  handleShowPhone(){
    wx.showToast({
      title: this.data.community.leader.phone,
      icon: "none"
    })
  },
  onShow(){
    console.log("页面一展示就执行");
    wx.getStorage({
      key: "userInfo", 
      success: (res)=>{
        this.handleFindCommunity(res.data.id);
      }
    })
  },
  handleNavigateToChangeGroup(){
    const id = this.data.community.id
    console.log("切换拼团:",id);
    wx.navigateTo({
      url: `/pages/group/group?id=${id}`,
    })
  },
  navigateToDetailPage: function (e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}`,
      success: function () {
        console.log('跳转成功');
      },
      fail: function (err) {
        console.log('跳转失败', err);
      }
    });
  },
  navigateToJoinGroupPage: function (e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/joinGroup/joinGroup?id=${id}`,
      success: function () {
        console.log('跳转成功');
      },
      fail: function (err) {
        console.log('跳转失败', err);
      }
    });
  },
  navigateToGroup: function () {
    // 导航到拼团页面逻辑
    if (!this.data.isGroupActive) {
      this.setData({
        isGroupActive: true,
        isMyActive: false
      });
    }
  },
  handleNavigateToMine(){
    wx.navigateTo({
      url: '/pages/mine/mine',
    })
  },
  handleInput(e) {
    const inputValue = e.detail.value;
    this.setData({
      "queryPageBean.queryString": inputValue
    });
    console.log("分页条件:",this.data.queryPageBean.queryString);
    this.handleFindPage()
  },
  handleJoinGroup: function (e) {
    // 处理立即拼团点击事件，可在此添加拼团逻辑
    console.log('点击拼团:', e.currentTarget.dataset.id);
  },
  navigateToGroup: function () {
    // 导航到拼团页面逻辑
    if (!this.data.isGroupActive) {
      this.setData({
        isGroupActive: true,
        isMyActive: false
      });
    }
  },
  navigateToMyPage: function () {
    // 导航到我的页面逻辑
    if (!this.data.isMyActive) {
      this.setData({
        isGroupActive: false,
        isMyActive: true
      });
    }
  },
  handleFindPage: function(){
    wx.request({
      url: 'http://localhost:9301/group/findPage',
      method:"POST",
      data:{
        currentPage: this.data.queryPageBean.currentPage,
        pageSize: this.data.queryPageBean.pageSize,
        queryString: this.data.queryPageBean.queryString,
        status: 1,
        communityId: this.data.community.id
      },
      success: (res) => {
        console.log("数据查询成功",res.data.rows);
        this.setData({
          products: res.data.rows
        })
        this.startCountdown(this.data.products);
      }
      
    })
  },
  startCountdown(groups) {
    groups.forEach((group, index) => {
        // 将日期字符串转换为时间戳
        const endTime = new Date(group.endTime.replace(/-/g, '/')).getTime();
        const intervalId = setInterval(() => {
            const now = new Date().getTime();
            const diff = endTime - now;
            if (diff <= 0) {
                // 倒计时结束
                clearInterval(intervalId);
                group.countdownText = '已结束';
            } else {
                const days = Math.floor(diff / (1000 * 60 * 60 * 24));
                const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
                const seconds = Math.floor((diff % (1000 * 60)) / 1000);
                group.countdownText = `${days}天 ${hours}小时 ${minutes}分 ${seconds}秒`;
            }
            // 更新页面上的倒计时文本
            this.setData({
                [`products[${index}].countdownText`]: group.countdownText
            });
        }, 1000);
        // 将定时器 ID 保存到数组中
        this.data.intervalIds.push(intervalId);
    });
  },
  onUnload() {
     // 清除所有定时器
     this.data.intervalIds.forEach((intervalId) => {
      clearInterval(intervalId);
  });
  // 清空保存定时器 ID 的数组
  this.setData({
      intervalIds: []
  });
  },
  onLoad() {
    this.handleShowDialog();
    
    // this.handleFindPage()
  },
  // 请求微信登录对话框
  handleShowDialog(){
    wx.showModal({
      title: '登录',
      content: '请您使用微信登录',
      showCancel: false,
      complete: (res) => {
        if (res.cancel) {
          console.log("no");
        }
        if (res.confirm) {
          this.handleGetUserProfile()
        }
      }
    })
  },
  // 获取用户登录信息并向后端发送
  handleGetUserProfile(){
    this.handleLogin(),
    wx.getUserProfile({
      desc: 'desc',
      success: (res) => {
        this.setData({
          'userInfo.nickName': res.userInfo.nickName,
          guest: false,
          'userInfo.avatarUrl': res.userInfo.avatarUrl,
        })
        console.log("微信用户信息：",res.userInfo);
        wx.request({
          url: 'http://localhost:9301/user/login', // 替换为你后端服务器的接口地址
          method: 'POST', // 根据后端接口要求选择合适的请求方法，如 GET、POST 等
          header: {
            'content-type': 'application/json' // 默认值就是这个，明确指定更保险
          },
          data: {
            // 将用户信息作为参数传递
            nickName: this.data.userInfo.nickName,
            avatarUrl: this.data.userInfo.avatarUrl,
            openId: this.data.userInfo.openId,
            sessionKey: this.data.userInfo.sessionKey,
          },
          success: (res) => {
            this.setData({
              'userInfo.id': res.data.data.userId
            })
            wx.setStorage({
              key: "userInfo",
              data: this.data.userInfo,
              encrypt: true,
            })
            if(res.data.data.newUser){
              wx.navigateTo({
                url: '/pages/choseCommuntiy/choseCommuntiy',
                success: (res)=>{
                  console.log("跳转了");
                }
              })
            }
            this.handleFindCommunity(res.data.data.userId);
            console.log('数据发送成功', res.data);
            
          },
          fail: (err) => {
            console.log('数据发送失败', err);
          }
        });
      },
      fail: (res)=>{
        this.handleShowDialog();
      }
    })
    
  },
  // 获取openId
  handleLogin() {
  // 登录
    wx.login({
        success: res => {
            if (res.code) {
                let URL = 'https://api.weixin.qq.com/sns/jscode2session?appid=wx0c57f6714a5f52ac&secret=6c93b6954b476a4c501b21a94a1f2a97&js_code=';
                wx.request({
                    url: URL,
                    success: function (res) {
                        this.setData({
                            "userInfo.openId": res.data.openid,
                            "userInfo.sessionKey": res.data.session_key
                        });
                    }.bind(this), // 使用 bind 方法将 this 绑定为页面实例
                    fail: function (err) {
                        console.log('请求失败', err);
                    }
                });
            }
        }
      });
  },
  // 下啦刷新
  onPullDownRefresh() {
    console.log('触发下拉刷新');
    setTimeout(()=>{
        console.log("延迟1秒");
        wx.stopPullDownRefresh()
        this.handleFindPage();
    },1000)
    // 模拟刷新数据
    console.log("刷新了");
  },
  // 加载更多分页查询
  handleLoadMore(){
    console.log("进来了");
    let size = this.data.queryPageBean.pageSize
    this.setData({
      "queryPageBean.pageSize":size+5
    })
    console.log(this.data.queryPageBean);
    this.handleFindPage()
  },
  // 上拉加载更多
  onReachBottom() {
    console.log("刷新更多");
    try {
      this.handleLoadMore();
    } catch (error) {
      console.error('handleLoadMore 方法出错:', error);
    }
    setTimeout(()=>{
      console.log("延迟1秒");
      wx.stopPullDownRefresh()
      this.handleFindPage();
  },1000)
  },
  // 查询当前用户的社区
  handleFindCommunity(id){
    console.log("查询当前用户的社区参数:",id);
    wx.request({
      url: `http://localhost:9301/community/findByUserId?id=${id}`,
      method:"GET",
      success: (res)=>{
        console.log("查询当前用户的社区",res);
        if(res.data.data == null){
          
        }
        this.setData({
          community: res.data.data
        })
        this.handleFindPage()
      }
    })
    
  }
});